package com.miaoquan.mqcommon.exception;


import com.miaoquan.mqcommon.api.CommonResult;
import com.miaoquan.mqcommon.api.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理
 * Created by macro on 2020/2/27.
 */
@Slf4j
@ResponseBody
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = ApiException.class)
    public CommonResult<Object> handle(ApiException e) {
        if (e.getErrorCode() != null) {
            return CommonResult.failed(e.getErrorCode());
        }
        return CommonResult.failed(e.getMessage());
    }

    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    public CommonResult<Object> exceptionHandler(MissingServletRequestParameterException e) {
//        log.error(e.getMessage(), e);
        return CommonResult.failed(ResultCode.VALIDATE_FAILED,e.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    public CommonResult<Object> exceptionHandler(Exception e) {
        log.error(e.getMessage(), e);
        return CommonResult.failed(ResultCode.UNKNOW);
    }

}
